import time
import random
import base64
import uuid
from urllib.parse import urlparse
import re

import requests
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend


def parse_url_params(url):
    """解析URL参数"""
    params = {}
    pattern = re.compile(r'(\w+|[\u4e00-\u9fa5]+)=(\w+|[\u4e00-\u9fa5]+)')
    matches = pattern.findall(url)

    for match in matches:
        key = match[0]
        value = match[1]
        params[key] = value

    return params


def sort_map_keys_and_join_values(input_map):
    """排序并拼接参数值"""
    sorted_keys = sorted(input_map.keys())
    joined_values = ''.join(str(input_map[key]) for key in sorted_keys)
    return joined_values


def process_path(url):
    """处理URL路径"""
    parsed_url = urlparse(url)
    path = parsed_url.path

    if path.startswith('/'):
        second_slash = path.find('/', 1)
        if second_slash != -1:
            processed_path = path[second_slash:]
        else:
            processed_path = ""
    else:
        processed_path = path

    return processed_path


def generate_random_string(length=14):
    """生成随机字符串"""
    chars = "abcdefghijklmnopqrstuvwxyz0123456789"
    return ''.join(random.choices(chars, k=length))

def rsa_encrypt_pkcs1_only(text):
    url = "http://8.140.232.101:3000/encrypt"
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "text": text
    }

    print(f"🔐 通过HTTP服务加密:")
    print(f"   明文: '{text}'")

    response = requests.post(url, headers=headers, json=data, timeout=10)

    print(f"   响应状态: {response.status_code}")
    print(f"   响应内容: {response.text}")
    response.raise_for_status()
    data = response.json()

    return data.get("data").get("encrypted")


def get_headers(url: str, token: str=""):
    """
    生成请求头 - 尝试多种加密方式
    """
    # 每次请求生成新的时间戳和随机数
    x_timestamp = str(int(time.time() * 1000))
    x_nonce = generate_random_string(14)

    # 处理URL组件
    path = process_path(url)
    query_params = parse_url_params(url)
    s = sort_map_keys_and_join_values(query_params)

    print("🔍 参数详情:")
    print(f"   URL: {url}")
    print(f"   Path: '{path}'")
    print(f"   参数: {query_params}")
    print(f"   排序键: {sorted(query_params.keys())}")
    print(f"   拼接值(s): '{s}'")
    print(f"   时间戳: {x_timestamp}")
    print(f"   随机数: {x_nonce}")
    print(f"   Token: {token}")

    # 构造加密明文
    plain_text = path + s + x_timestamp + x_nonce + token
    print(f"📝 完整明文:")
    print(f"   '{plain_text}'")
    print(f"   总长度: {len(plain_text)} 字符")
    # 首先尝试cryptography库
    x_sign = rsa_encrypt_pkcs1_only(plain_text)
    # 设置请求头
    headers = {
        "x-nonce": x_nonce,
        "x-timestamp": x_timestamp,
        "x-sign": x_sign,
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        "referer": "https://yuyue.tamgw.beijing.gov.cn/team.html?date=2025-09-05&week=5&productId=11324",
        "uuid": str(uuid.uuid4()),
        "content-type": "application/json"
    }

    print("\n✅ 生成的请求头:")
    for key, value in headers.items():
        if key == "x-sign":
            print(f"   {key}: {value[:80]}...")
        else:
            print(f"   {key}: {value}")

    return headers


# 使用示例
if __name__ == "__main__":
    test_url = "https://yuyue.tamgw.beijing.gov.cn/api-system/send_sms/send?_=1759920215200"
    test_token = "YOUR_ACTUAL_TOKEN_HERE"  # 替换为真实token

    headers = get_headers(test_url, test_token)
    print(f"\n🎯 请求头生成完成")